import request from "../utils/request";
const max = 4
let count = 0

// 大文件分片上传
export default function (callBack, file, option) {
	// let ext = file.name.slice(file.name.lastIndexOf(".")).toLowerCase();
	// var _this = this;
	// if (!fileValid(ext)) return this.$message.warning("请上传规定文件");
	let bytesPerPiece = 5 * 1024 * 1024 // 每个文件切片大小定为5MB .
	let md5 = getMd5()
	count = 0
	cutFileUpload(callBack, file, 0, bytesPerPiece, md5, option)
}

function cutFileUpload(callBack, file, index, bytesPerPiece, md5, option) {
	let uploadLoadingize = file.size
	let start = index * bytesPerPiece
	let end = start + bytesPerPiece
	if (end > uploadLoadingize) {
		end = uploadLoadingize
	}
	let chunk = file.slice(start, end) // 切割文件
	let fData = new FormData()
	fData.append("file", chunk)
	fData.append("md5", md5)
	request.post("/File/CutFileUpload", fData)
		.then(res => {
			if (end >= uploadLoadingize) {
				callBack("全部切片上传完成", "99")
				mergeFile(callBack, md5, file.name, option)
			} else {
				const uploadProgress = ((99 * end) / uploadLoadingize).toFixed(0)
				callBack("部分切片上传完成", uploadProgress)
				cutFileUpload(callBack, file, index + 1, bytesPerPiece, md5, option)
			}
		})
		.catch(err => {
			count++
			if (count < max) {
				console.log(err, "分片上传失败，重新上传中...")
				cutFileUpload(callBack, file, index, bytesPerPiece, md5, option)
			} else {
				console.log(err, "分片上传失败，取消上传")
				callBack("切片上传失败", uploadProgress)
			}
		})
}

function mergeFile(callBack, md5, name, option) {
	// 合并切片
	let fDataMerge = new FormData()
	fDataMerge.append("md5", md5)
	fDataMerge.append("name", name)
	for (let key in option) {
		if (key !== "id" && key != "index") {
			fDataMerge.append(key, option[key])
		}
	}
	request({
		url: "/File/MergeFile",
		method: 'post', data: fDataMerge, timeout: 10 * 60 * 1000,
	})
		.then(res => {
			console.log(res, 'res')
			if (res.path) {
				callBack("合并完成", 100, res, option["id"], option["index"])
			} else {
				callBack("合并失败", 99, res)
			}
		})
		.catch(err => {
			count++
			if (count < max) {
				console.error(err, "合并失败，重新合并中...")
				mergeFile(callBack, md5, name, option)
			} else {
				callBack("合并失败", 99, res)
			}
		})
}

function getMd5() {
	var d = new Date().getTime()
	var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
		var r = (d + Math.random() * 16) % 16 | 0
		d = Math.floor(d / 16)
		return (c == "x" ? r : (r & 0x3) | 0x8).toString(16)
	})
	return uuid
}